<template>
  <a-spin :spinning="myLoading">
    <a-select
      show-search
      :allowClear="true"
      style="{width: '100%'}" 
      v-model="value" 
      placeholder="请输入人员编码或姓名"
      :default-active-first-option="false"
      :show-arrow="false"
      :filter-option="false"
      :not-found-content="null"
      @search="handleSearch"
      @change="handleChange"
    >
      <a-select-option v-for="d in data" :key="d.value">
        {{ d.text }}
      </a-select-option>
    </a-select>
  </a-spin>
</template>
<script>

  import {
    getUrl
  } from '@/api/manage'
let timeout
let currentValue

function fetch(value, callback, param) {
  if (timeout) {
    clearTimeout(timeout)
    timeout = null
  }
  currentValue = value

  function fake() {
    getUrl('cutUser/get4Search' , param)
      .then(dataResult => {
       if (currentValue === value) {
                 const datas = dataResult.result
                 const data = []
                 datas.forEach(r => {
                   data.push({
                     value: r['id'],
                     text: r['name'],
                     title: r['title'],
                     name : r['tname'],
                     dId : r['dId'],
                     
                   })
                 })
                 
                 callback(data)
               }
       
      })
  }

  timeout = setTimeout(fake, 300)
}
export default {
  props: {
    settings : {
       style : null,
       id    : '',
       departmentId: '',
       params: {},
    }
  },
  data() {
    return {
      data: [],
      value:  '',
      myLoading : false,
    }
  },
  methods: {
    handleSearch(value) {
      var departmentId = ''
      if(this.settings && this.settings.departmentId){
        departmentId = this.settings.departmentId
      }
      fetch(value, data => (this.data = data), {departmentId : departmentId, name : value})
    },
    handleChange(value) {
      var departmentId = ''
      if(this.settings && this.settings.departmentId){
        departmentId = this.settings.departmentId
      }
      fetch(value, this.callback, {id : value, departmentId: departmentId, })
    },
    callback(data){
      this.data = data
      var id = ''
      var v2 = []
      if(this.data.length > 0){
        id = this.data[0].value
        v2 = this.data[0]
      } 
      this.value = id
      this.$emit('change', id, v2, this.settings?this.settings.id : '') 
       this.myLoading = false
    },
    setDefault(value){
      this.myLoading = true
      this.handleChange(value)
    },
    clear(){
      this.data = []
       this.value = ''
    }
    
  },
}
</script>